package cn.itcast.config;

import cn.itcast.domain.Conversation;
import cn.itcast.mapper.ConversationMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class MysqlChatMemory implements ChatMemory {
    private static final Logger logger = LoggerFactory.getLogger(MysqlChatMemory.class);

    @Autowired
    private ConversationMapper conversationMapper;


    /**
     * 保存数据
     * @param conversationId
     * @param messages
     */
    @Override
    public void add(String conversationId, List<Message> messages) {
        LocalDateTime now = LocalDateTime.now();
        for (Message m : messages) {
            try {
                Conversation conversation = Conversation.builder()
                        .type(m.getMessageType().getValue())
                        .message(m.getText())
                        .conversationId(conversationId)
                        .createTime(now)
                        .build();
                conversationMapper.insert(conversation);
            } catch (Exception e) {
                logger.error("保存对话记录失败: conversationId={}, message={}", conversationId, m.getText(), e);
                // 继续处理其他消息而不是中断整个过程
            }
        }
    }

    /**
     * 查询对应的消息
     * @param conversationId
     * @return
     */
    @Override
    public List<Message> get(String conversationId) {
        //select * from conversation where conversation_id = ?
        List<Conversation> conversations = conversationMapper.selectList(
                new LambdaQueryWrapper<Conversation>()
                .eq(Conversation::getConversationId, conversationId));
        return conversations.stream().map(c->{
            Message message = null;
            if (MessageType.USER.getValue().equals(c.getType())) {
                message =  new UserMessage(c.getMessage());
            }else if (MessageType.ASSISTANT.getValue().equals(c.getType())) {
                message = new AssistantMessage(c.getMessage());
            }
            return message;
        }).toList();
    }

    /**
     * 删除所有的对话
     * @param conversationId
     */
    @Override
    public void clear(String conversationId) {
        //delete from conversation where conversation_id = ?
        conversationMapper.delete(new LambdaQueryWrapper<Conversation>().eq(Conversation::getConversationId,conversationId));
    }

}